//$Id:MysqlJdbcDAOImpl.java 2010-1-4 下午03:19:42
package com.walllee.core.dao.support;

import java.util.List;

import com.walllee.core.dao.AbstractJdbcDAO;
import com.walllee.core.dao.Page;
import com.walllee.core.util.PageUtil;

/**
 * 
 *
 * @author Wall.Lee(xiaoshan2242@gmail.com)
 */
public class MysqlJdbcDAOImpl extends AbstractJdbcDAO{

	/* (non-Javadoc)
	 * @see com.walllee.core.dao.AbstractJdbcDAO#getIdentity(java.lang.String)
	 */
	@Override
	public String getIdentity(String sequenceName) {
		return "";
	}

	/* (non-Javadoc)
	 * @see com.walllee.core.dao.JdbcDAO#queryPage(java.lang.String, java.lang.Object[], int, int)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Page queryPage(String sql, Object[] prameters, int page, int pageSize) {
		int totalCount = this.queryForRowCount(sql, prameters); 
		int _page = PageUtil.getRealCurePage ( page , totalCount , pageSize );
		int startIndex = PageUtil.page2Index( totalCount , _page , pageSize ) ;
		
		//初始化分页的参数
		Object[] limitParameter = new Object[2];
		limitParameter[ 0 ] = startIndex ;
		limitParameter[ 1 ] = pageSize ;
		
		Object[] newParameters = null ;
		if ( prameters == null || prameters.length < 1 ){
			newParameters = limitParameter ;
		}else{
			int size = prameters.length ;
			newParameters = new Object[2 + size ] ;
			System.arraycopy(prameters, 0, newParameters, 0 , size );
			System.arraycopy(limitParameter , 0 , newParameters , size - 1 , 2 ) ;
		}
		String _sql = getLimitSql(sql) ;
		List _data = this.getJdbcTemplate().queryForList( _sql, newParameters) ;
		Page pageInfo = new Page( _data , totalCount , pageSize , _page );
		
		return pageInfo ;
	}
	
	/**
	 * 获取mysql分页的语句
	 * @param sql
	 * @return
	 */
	private String getLimitSql(final String sql){
		return new StringBuffer( sql.length()+20 )
				.append(sql)
				.append(" limit ?, ? ")
				.toString();
	}

}
